package com.cwj.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Clone the Fraud Detection service repository locally.
 * @author wujie.chen
 * 2021/10/14 17:46
 */
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(8888);
        ExecutorService executorService = Executors.newCachedThreadPool();

        while(true){
            Socket connect = server.accept();
            executorService.execute(new ServerHandler(connect));
        }
    }

    public static class ServerHandler implements Runnable{
        private final Socket socket;

        public ServerHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try(InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader bufferedreader = new BufferedReader(isr);

                OutputStream os = socket.getOutputStream();
                PrintWriter printwriter = new PrintWriter(os);
                ){
                StringBuilder stringBuilder = new StringBuilder();
                String s;
                while((s = bufferedreader.readLine())!=null){
                    stringBuilder.append(s);
                }
                System.out.println(stringBuilder.toString());
                socket.shutdownInput();

                // 回复
                printwriter.write(stringBuilder.toString());
                printwriter.flush();
                socket.shutdownOutput();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
